<?php

/**
 * CatalogController
 * 
 * @author MF
 * @version 2.0
 */

require_once 'Zend/Controller/Action.php';

class Cms_CatalogController extends Zend_Controller_Action {
	
	
	public function indexAction() {
		CmsAuth::check();
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		$this->view->catalog_id = $id;
		
		$main = MF_Main::getInstance();
		$cat = $main->Catalog->getById($id);
		
		$category_columns = array();
		$data_key_names = array_keys($cat->config['category']);
		for ($k=0;$k<count($data_key_names);$k++) {
			array_push($category_columns,$cat->config['category'][$data_key_names[$k]][2]);
		}
		$this->view->category_data_map = $category_columns;
		
		$item_columns = array();
		$data_key_names = array_keys($cat->config['item']);
		for ($k=0;$k<count($data_key_names);$k++) {
			array_push($item_columns,$cat->config['item'][$data_key_names[$k]][2]);
		}
		
		$this->view->data_map = $item_columns;
		$this->view->edit_categ = $main->_config->catalog->category_edit == null ? '0' : $main->_config->catalog->category_edit;
	}
	
	
	public function dataAction() {
		CmsAuth::check();
		
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		if (NULL === $cat_id = $this->getRequest()->getParam('cat_id')) {
			throw new Zend_Controller_Action_Exception('Required param "Cat Id"', 404);
		}
		
		$cat = MF_Main::getInstance()->Catalog->getById($id);
		
		if (NULL !== $act = $this->getRequest()->getParam('act')) {
			switch ($act) {
				case 'add':
					$new_item = $cat->addItem();
					$new_item->link($cat_id);
					break;
				
				case 'del':
					if (NULL === $item_id = $this->getRequest()->getParam('item_id')) {
						throw new Zend_Controller_Action_Exception('Required param "Item_Id" while del action precessed', 404);
					}
					
					try {
						// в случае если позиция из каталога уже удалена выскочит эксепшен
						$cat->getItemById($item_id)->delete();
					} catch (Exception $e) {}
					
					break;
					
				default:
					;
				break;
			}
			
		}
		
		
		$goods_list = $cat->filter();
		
		$goods_list->appendCategoryCondition($cat_id);
		
		if ((NULL !== $limit_from = $this->getRequest()->getParam('limit_from')) 
			&& (NULL !== $limit_amount = $this->getRequest()->getParam('limit_amount'))) {
				$goods_list->setLimits($limit_from,$limit_amount);
			}
		
		
		
		$goods_list->Make();
		
		$goods = array();
		for ($g=0;$g<$goods_list->length();$g++) {
			$good = $goods_list->item($g);
			
			$category_path = array();
			for ($c=0;$c<$good->category_length();$c++) {
				$current_category = $good->category_item($c);
				$path2categ = array();
				while (true) {
					
					if ($current_category->_content_id!='0') {
						array_push($path2categ,'/'.$current_category->name);
						$current_category = $current_category->parentCategory();
					} else {
						array_push($path2categ,'/Корневая');
						break;
					}
					
				}
				
				array_push($category_path,implode('',array_reverse($path2categ)));
			}
			
			$goodNode = array(
					array('cat_item_name',array('id' => $good->_content_id, 'value' => $good->name=="" ? "Название не указано" : $good->name)),
					array('cat_item_categories',array('id' => $good->_content_id, 'value' => implode('; ',$category_path)))
				);
				
				
			$item_columns = array();
			$data_key_names = array_keys($cat->config['item']);
			for ($k=0;$k<count($data_key_names);$k++) {
				$key_name = $data_key_names[$k];
					
				if (gettype($good->$key_name)=='object') {
					array_push($goodNode,$this->_helper->WidgetAbstract($good->$key_name));
				} else {
					array_push($goodNode,array($key_name,array('id' => $good->_content_id, 'value' => $good->$key_name)));
				}
			}
			
			array_push($goodNode,array('cat_item_delete',array('id' => $good->_content_id )));
			
			array_push($goods,$goodNode);
		}
		

		$this->view->data = array('total_length' => $goods_list->total_length(), 'data' => $goods); 
		$this->renderScript('json.phtml');
	}
	
	
	public function changeAction() {
		CmsAuth::check();
		
		if (NULL === $cat_id = $this->getRequest()->getParam('cat_id')) {
			throw new Zend_Controller_Action_Exception('Required param "Cat Id"', 404);
		}
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		$catalogItem = MF_Main::getInstance()->Catalog->getById($cat_id)->getItemById($id);
		
		if (NULL !== $title = $this->getRequest()->getParam('title')) {
			$title = $title; 
			$catalogItem->name = $title;
			$this->view->result = 1;
		}
		
		if (NULL !== $price = $this->getRequest()->getParam('price')) {
			$price = $price; 
			$catalogItem->price = $price;  // TODO make here datatyope chekin'
			$this->view->result = 1;
		}
		
		if (NULL !== $new_f = $this->getRequest()->getParam('new_f')) {
			$new_val = $catalogItem->new_f=='1' ? '0' : '1';
			$catalogItem->new_f = $new_val;
			$this->view->result = $new_val;
		}
		
		if (NULL !== $sales_leader_f = $this->getRequest()->getParam('sales_leader_f')) {
			$new_val = $catalogItem->sales_leader_f=='1' ? '0' : '1';
			$catalogItem->sales_leader_f = $new_val;
			$this->view->result = $new_val;
		}
		
		$this->_helper->layout->disableLayout();
	}
	
	public function categorylinkAction() {
		CmsAuth::check();
		
		if (NULL === $cat_id = $this->getRequest()->getParam('cat_id')) {
			throw new Zend_Controller_Action_Exception('Required param "Cat Id"', 404);
		}
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		$catalog = MF_Main::getInstance()->Catalog->getById($cat_id);
		$item = $catalog->getItemById($id);
		
		$checked_categories = array();
		for ($c=0;$c<$item->category_length();$c++) {
			array_push($checked_categories,$item->category_item($c)->_content_id);
		}
		
		if ($this->_request->isPost()) {
			$post_data = $this->_request->getPost();
			
			for ($cc=0;$cc<count($checked_categories);$cc++) {
				$item->unlink($checked_categories[$cc]);
			}
			
			$checked_vals = isset($post_data['category']) ? $post_data['category'] : array();
			for ($cv=0;$cv<count($checked_vals);$cv++) {
				$item->link($checked_vals[$cv]);
			}
			
			$this->renderScript('exit.phtml');
			return true;
		} else {
			
			$this->view->categories = $catalog->CategoryList();
			
			$this->view->checked_categories = $checked_categories;
		}
		
		
	}
	
	public function categorylistAction() {
		CmsAuth::check();
		
		if (NULL === $cat_id = $this->getRequest()->getParam('cat_id')) {
			throw new Zend_Controller_Action_Exception('Required param "Cat Id"', 404);
		}
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		$item = MF_Main::getInstance()->Catalog->getById($cat_id)->getItemById($id);
		
		$category_path = array();
		for ($c=0;$c<$item->category_length();$c++) {
			$current_category = $item->category_item($c);
			$path2categ = array();
			while (true) {
					
				if ($current_category->_content_id!='0') {
					array_push($path2categ,'/'.$current_category->name);
					$current_category = $current_category->parentCategory();
				} else {
					array_push($path2categ,'/Корневая');
					break;
				}
				
			}
			
			array_push($category_path,implode('',array_reverse($path2categ)));
		}
		
		$this->view->result = count($category_path)==0? '0' : implode('; ',$category_path);
		
		$this->_helper->layout->disableLayout();
	}
	
	public function pathAction() {
		
		CmsAuth::check();
		
		if (NULL === $cat_id = $this->getRequest()->getParam('cat_id')) {
			throw new Zend_Controller_Action_Exception('Required param "Cat Id"', 404);
		}
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		$path = array();
		
		$item = MF_Main::getInstance()->Catalog->getById($cat_id)->getCategoryById($id);
		
		while (true) {
			$sub_categ = array();
			for ($s=0;$s<$item->length();$s++) {
				array_push($sub_categ,
					array(
						'id' => $item->item($s)->_content_id,
						'name' => $item->item($s)->name
					));
			}
			
			if ($item->_content_id==0) {
				array_push($path,
					array(
						'id' => 0,
						'name' => 'Корневая',
						'sub' => $sub_categ
					));
				break;
			} else {
				array_push($path,
					array(
						'id' => $item->_content_id,
						'name' => $item->name,
						'sub' => $sub_categ
					));
			}
			
			
			$item = $item->parentCategory();
		};
		
		$this->view->path_structure = array_reverse($path);
		
		$this->_helper->layout->disableLayout();
	}

	
	public function changecategAction() {
		CmsAuth::check();
		
		if (NULL === $cat_id = $this->getRequest()->getParam('cat_id')) {
			throw new Zend_Controller_Action_Exception('Required param "Cat Id"', 404);
		}
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		$categoryItem = MF_Main::getInstance()->Catalog->getById($cat_id)->getCategoryById($id);
		
		if (NULL !== $title = $this->getRequest()->getParam('title')) {
			$title = $title; 
			$categoryItem->name = $title;
			$this->view->result = 1;
		}
		
		$this->_helper->layout->disableLayout();
	}
	
	public function datacategAction() {
		CmsAuth::check();
		
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		if (NULL === $cat_id = $this->getRequest()->getParam('cat_id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		$cat = MF_Main::getInstance()->Catalog->getById($cat_id);
		$categItem = $cat->getCategoryById($id);
		
		if (NULL !== $act = $this->getRequest()->getParam('act')) {
			switch ($act) {
				case 'add':
					$categItem->add();
					break;
				
				case 'del':
					if (NULL === $item_id = $this->getRequest()->getParam('item_id')) {
						throw new Zend_Controller_Action_Exception('Required param "Item_Id" while del action precessed', 404);
					}
					
					try {
						// в случае если позиция из каталога уже удалена выскочит эксепшен
						$cat2delete = $cat->getCategoryById($item_id);
						for ($i=0;$i<$cat2delete->items->length();$i++) {
							$cat2delete->items->item($i)->delete();
						}
						$cat2delete->delete();
					} catch (Exception $e) {}
					
					break;
					
				default:
					;
				break;
			}
			
		}
		
		
		
		
		$categ_list = array();
		for ($c=0;$c<$categItem->length();$c++) {
			$categ_row = 
				array(
					array('category_name', array('id' => $categItem->item($c)->_content_id,'value' => $categItem->item($c)->name)));
					
			$data_key_names = array_keys($cat->config['category']);
			for ($k=0;$k<count($data_key_names);$k++) {
				$key_name = $data_key_names[$k];
				if (gettype($categItem->item($c)->$key_name)=='object') {
					array_push($categ_row,$this->_helper->WidgetAbstract($categItem->item($c)->$key_name));
				} else {
					array_push($categ_row,array($key_name,array('id' => $categItem->item($c)->_content_id, 'value' => $categItem->item($c)->$key_name)));
				}
			}
					
			array_push($categ_row,
					array('category_delete', array('id' => $categItem->item($c)->_content_id)));
				
			array_push($categ_list,$categ_row);
		}
		

		$this->view->data = $categ_list; 
		$this->renderScript('json.phtml');
	}
	
	
	public function catalogparametrsAction() {
		 CmsAuth::check();
		
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		if (NULL === $cat_id = $this->getRequest()->getParam('cat_id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		$cat = MF_Main::getInstance()->Catalog->getById($cat_id);
		$item = $cat->getItemById($id);
		
		if ($this->_request->isPost()) {
			$post_data = $this->_request->getPost();
			$params = array();
			for ($p=0;$p<count($cat->parameters);$p++) {
				$params[$cat->parameters[$p][0]] = $post_data[$cat->parameters[$p][0]];
			}
			$item->catalog_parameters = $params;
			
			$this->renderScript('exit.phtml');
			return true;
		}
		
		$this->view->param_list = $cat->parameters;
		$this->view->param_values = $item->catalog_parameters;
	}
	
	
	public function optionalparametrsAction() {
		 CmsAuth::check();
		
		
		if (NULL === $id = $this->getRequest()->getParam('id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		if (NULL === $cat_id = $this->getRequest()->getParam('cat_id')) {
			throw new Zend_Controller_Action_Exception('Required param "Id"', 404);
		}
		
		$cat = MF_Main::getInstance()->Catalog->getById($cat_id);
		$item = $cat->getItemById($id);
		
		
		if ($this->_request->isPost()) {
			$post_data = $this->_request->getPost();
			$params = array();
			for ($p=0;$p<count($post_data['param_key']);$p++) {
				$params[$post_data['param_key'][$p]] = $post_data['param_value'][$p];
			}
			$item->parameters = $params;
			
			$this->renderScript('exit.phtml');
			return true;
		}
		
		$param_values = array();
		$param_keys = array_keys($item->parameters);
		for ($k=0;$k<count($param_keys);$k++) {
			array_push($param_values,array($param_keys[$k],$item->parameters[$param_keys[$k]]));
		}
		
		$this->view->param_list = $param_values;
		
	}
	
}

